import request from '../utils/request'

//收集积分
export const collectUserPoint = (data) => {
  let point = localStorage.getItem('point')
  point = point ? JSON.parse(point) : []
  return new Promise((response, reject) => {
    if (point.length <= 0 || !point.includes(data.channel)) {
      response({ code: '-1', message: '积分获取上限' })
    }
    let tipsMsg = null
    request({
      url: '/point/collectUserPoint',
      method: 'post',
      data,
    })
      .then((res) => {
        if (res.code === '0' || res.code === '-49') {
          if (data.channel !== 10) {
            const index = point.indexOf(data.channel)
            if (index !== -1) {
              point.splice(index, 1)
              localStorage.setItem('point', JSON.stringify(point))
            }
          }
          tipsMsg = res.code === '0' ? { code: '0', message: '积分+10' } : { code: '-49', message: '积分上限', channel: data.channel }
        }
        response(tipsMsg)
      })
      .catch((err) => {
        response({ code: '-9999', message: '服务错误' })
      })
  })
}
